package org.example.demo.bundle;

import javafx.beans.binding.Bindings;
import javafx.scene.control.Labeled;

import java.lang.reflect.Field;

public class I18NBinder {
    public static void bind(Object controller) {
        for (Field field : controller.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(I18N.class)) {
                I18N annotation = field.getAnnotation(I18N.class);
                String key = annotation.value();
                field.setAccessible(true);
                try {
                    Labeled control = (Labeled) field.get(controller);
                    bindText(control, key);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void bindText(Labeled control, String key) {
        control.textProperty().bind(
                Bindings.createStringBinding(
                        () -> ResourceManager.getInstance().getString(key),
                        ResourceManager.getInstance().currentLocaleProperty()
                )
        );
    }
}
